package ltd.hanamaki.study.jdbc.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/* 在工具类中 方法尽量使用 静态方法  属性尽量使用 静态*/
public class JDBCUtils_Druid {

    /* 连接信息 */
    static Properties properties;
    static Connection connection;
    static DataSource dataSource;
    /* 加载配置文件中的信息 */
    static {
        try {
            InputStream resourceAsStream = JDBCUtils_Druid.class.getClassLoader().getResourceAsStream("db.dbcp.properties");
            properties = new Properties();
            properties.load(resourceAsStream);
            /* 使用德鲁伊的方式 ；来 创建数据源 */
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
        }
    }

    /**
     * 连接数据库的方法
     * @return
     */
    public static Connection getCon() {
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet, PreparedStatement preparedStatement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}
